package com.mazaiting.testdemo.job

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.mazaiting.testdemo.R
import java.util.concurrent.TimeUnit

class JobActivity : AppCompatActivity() {
  private var jobScheduler: JobScheduler? = null
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_job)
  }
  
  /**
   * 开启Job服务
   */
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  fun onStartService(view: View) {
    // 获取JobScheduler服务
    jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
//    val time = 15 * 60 * 1000
    val time = 15
    // 指定哪个JobService执行操作
    val builder = JobInfo.Builder(1, ComponentName(this, TestJobService::class.java))
    if (time >= 15 * 60 * 1000) {
      // 设置重复时间, 单位ms
      builder.setPeriodic(15 * 60 * 1000)
      // 设置持久化
      builder.setPersisted(true)
      // 设置网络类型
      builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
    } else {
      // 执行最小延时时间
      builder.setMinimumLatency(TimeUnit.MILLISECONDS.toMillis(10))
      // 执行最长延时时间
      builder.setOverrideDeadline(TimeUnit.MILLISECONDS.toMillis(10))
      // 线性重试方案
      builder.setBackoffCriteria(TimeUnit.SECONDS.toMillis(10), JobInfo.BACKOFF_POLICY_LINEAR)
      // 未充电状态
      builder.setRequiresCharging(false)
    }
    // 执行任务
    jobScheduler!!.schedule(builder.build())
  }
  
  /**
   * 关闭Job服务
   */
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  fun onStopService(view: View) {
    jobScheduler?.cancel(1)
  }
}
